<template>
  <view class="person-container">
    <!-- 排序筛选 -->
    <view class="filter-container">
      <wd-drop-menu>
        <wd-drop-menu-item
          v-model="sortValue"
          :options="sortOptions"
          title="排序"
          icon="unfold-more"
          @change="handleSortChange"
        />
        <wd-drop-menu-item ref="filterDropMenu" title="筛选" icon="filter">
          <view>
            <wd-input
              v-model="queryParams.lastName"
              label="名"
              placeholder="请输入名"
            />
            <view class="flex-between py-2">
              <wd-button type="info" @click="handleResetQuery">重置</wd-button>
              <wd-button @click="handleQuery">查询</wd-button>
            </view>
          </view>
        </wd-drop-menu-item>
      </wd-drop-menu>
    </view>

    <!-- 数据列表 -->
    <view class="data-container">
      <!-- 登录人数据 -->
      <wd-card v-if="currentUserPerson" class="my-card">
        <!-- 扇形角标 -->
        <view class="corner-badge">
          <text class="corner-text">自己</text>
        </view>

        <template #title>
          <view class="flex-between">
            <view class="flex-center">
              <wd-img
                :width="50"
                :height="50"
                round
                :src="currentUserPerson.photoUrl || 'https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/fa6cbef09f834c41b7121841f6a9564e.png'"
              />
              <view class="ml-2">
                <view class="font-bold">
                  {{ currentUserPerson.firstName || "" }}
                  {{ currentUserPerson.lastName || "" }}
                  <wd-icon
                    v-if="currentUserPerson.gender === 1"
                    name="gender-male"
                    class="color-#4D80F0"
                  />
                  <wd-icon
                    v-else-if="currentUserPerson.gender === 2"
                    name="gender-female"
                    class="color-#FA4350"
                  />
                </view>
                <view class="mt-1">
                  <wd-text :text="currentUserPerson.roleNames || '暂无辈分'" size="12px" />
                </view>
              </view>
            </view>
            <view>
              <wd-tag v-if="currentUserPerson.alive === 1" type="success" plain>在世</wd-tag>
              <wd-tag v-else-if="currentUserPerson.alive === 0" plain>离世</wd-tag>
            </view>
          </view>
        </template>

        <wd-cell-group>
          <wd-cell title="配偶" :value="currentUserPerson.spouseName || '无'" icon="user-circle" />
          <wd-cell title="父亲" :value="currentUserPerson.parentName || '无'" icon="user" />
        </wd-cell-group>

        <template #footer>
          <view class="footer-block">
            <view class="text-left">
              <wd-text text="创建时间：" size="small" class="font-bold" />
              <wd-text :text="currentUserPerson.createTime || '-'" size="small" />
            </view>
            <view class="footer-btns flex-right">
              <wd-button
                type="primary"
                size="small"
                plain
                @click="handleEditPerson(currentUserPerson.id)"
              >
                编辑
              </wd-button>
              &nbsp;
              <wd-button
                v-if="!currentUserPerson.flag"
                type="info"
                size="small"
                plain
                @click="handleViewTree(currentUserPerson)"
              >
                查看家谱
              </wd-button>
            </view>
          </view>
        </template>
      </wd-card>

      <wd-card v-for="item in pageData" :key="item.id">
        <template #title>
          <view class="flex-between">
            <view class="flex-center">
              <wd-img
                :width="50"
                :height="50"
                round
                :src="item.photoUrl || 'https://boyangli.oss-cn-shanghai.aliyuncs.com/20250930/fa6cbef09f834c41b7121841f6a9564e.png'"
              />
              <view class="ml-2">
                <view class="font-bold">
                  {{ item.firstName }} {{ item.lastName }}
                  <wd-icon v-if="item.gender == 1" name="gender-male" class="color-#4D80F0" />
                  <wd-icon
                    v-else-if="item.gender == 2"
                    name="gender-female"
                    class="color-#FA4350"
                  />
                </view>
                <view class="mt-1">
                  <wd-text :text="item.genation || '暂无辈分'" size="12px" />
                </view>
              </view>
            </view>
            <view>
              <wd-tag v-if="item.alive === 1" type="success" plain>在世</wd-tag>
              <wd-tag v-else-if="item.alive === 0" plain>离世</wd-tag>
            </view>
          </view>
        </template>

        <wd-cell-group>
          <wd-cell title="配偶" :value="item.spouseName || '无'" icon="user-circle" />
          <wd-cell title="父亲" :value="item.parentName || '无'" icon="user" />
        </wd-cell-group>

        <template #footer>
          <view class="footer-block">
            <view class="text-left">
              <wd-text text="创建时间：" size="small" class="font-bold" />
              <wd-text :text="item.createTime" size="small" />
            </view>
            <view class="footer-btns flex-right">
              <wd-button type="primary" size="small" plain @click="handleEditPerson(item.id)">
                编辑
              </wd-button>
              &nbsp;
              <wd-button
                v-if="!item.flag"
                type="info"
                size="small"
                plain
                @click="handleViewTree(item)"
              >
                查看家谱
              </wd-button>
            </view>
          </view>
        </template>
      </wd-card>

      <wd-loadmore v-if="total > 0" :state="loadMoreState" @reload="loadmore" />
      <!-- <wd-status-tip v-else-if="total === 0" image="search" tip="当前搜索无结果" /> -->
      <!-- 没有成员数据空位展示 -->
      <view v-else-if="total === 0" class="no-data-container">
        <wd-button @click="handleAddPerson">添加成员</wd-button>
      </view>
    </view>

    <wd-message-box />
    <wd-popup v-model="editPopupVisible" lazy-render position="bottom" :close-on-click-modal="true">
      <view class="edit-form-card">
        <wd-input v-model="editForm.firstName" label="姓" required />
        <wd-input v-model="editForm.lastName" label="名" required />
        <wd-input v-model="editForm.nickname" label="昵称" />
        <wd-input v-model="editForm.genation" label="字辈" />
        <wd-select-picker
          v-model="editForm.gender"
          label="性别"
          :columns="genderOptions"
          placeholder="请选择性别"
          @change="handleChange"
        />
        <wd-select-picker
          v-model="editForm.alive"
          label="是否在世"
          :columns="aliveOptions"
          placeholder="请选择"
          @change="handleAliveChange"
        />
        <view class="avatar-upload">
          <label>头像照片</label>
          <AvatarUploader v-model="editForm.photoUrl" />
        </view>
        <wd-input v-model="editForm.occupation" label="职业" />
        <wd-input v-model="editForm.birthPlace" label="籍贯" />
        <wd-input v-model="editForm.address" label="地址" />
        <wd-input v-model="editForm.longitude" label="经度" />
        <wd-input v-model="editForm.latitude" label="纬度" />
        <wd-input v-model="editForm.birthDate" label="出生日期" type="date" placeholder="" />
        <wd-input v-model="editForm.deathDate" label="死亡日期" type="date" placeholder="" />
        <wd-textarea v-model="editForm.biography" label="个人简介" placeholder="请输入个人简介" />
      </view>
      <view class="popup-footer">
        <wd-button type="primary" @click="handleSaveEdit">提交</wd-button>
        <wd-button type="info" @click="editPopupVisible = !editPopupVisible">取消</wd-button>
      </view>
    </wd-popup>
  </view>
</template>

<script lang="ts" setup>
import { onLoad, onReachBottom } from "@dcloudio/uni-app";
import AvatarUploader from "@/components/AvatarUploader/AvatarUploader.vue";
import { ref, reactive } from "vue";
// @ts-ignore 类型声明问题
import { LoadMoreState } from "wot-design-uni/components/wd-loadmore/types";
// @ts-ignore 类型声明问题
import PersonAPI, { PageList, PageResponse } from "@/api/genealogy/person";
import UserAPI from "@/api/system/user";

// 修复类型错误，LoadMoreState 可能是 'loadmore' | 'loading' | 'nomore' | 'error'
const loadMoreState = ref<LoadMoreState>("loadmore" as LoadMoreState);
const filterDropMenu = ref();
const userInfo = uni.getStorageSync("user-info");

console.log(userInfo.userId);

// 存储当前登录用户的个人信息
const currentUserPerson = ref<any>(null);

const sortValue = ref(0);
const sortOptions = ref<Record<string, any>[]>([
  { label: "默认排序", value: 0 },
  { label: "最近创建", value: 1 },
  { label: "最近更新", value: 2 },
]);

let queryParams = reactive({
  lastName: "" as string | undefined,
  familyId: null as number | null,
  pageNum: 1,
  pageSize: 10,
  familyName: null as string | null, // 添加缺失的属性
});

const total = ref(0);
const pageData = ref<PageList[]>([]);

const editPopupVisible = ref(false);
const editForm = reactive<any>({});

const genderOptions = [
  { label: "男", value: 1 },
  { label: "女", value: 2 },
];

const aliveOptions = [
  { label: "在世", value: 1 },
  { label: "离世", value: 0 },
];
// 获取用户对应的自己的信息
const getUserInfo = async () => {
  try {
    const response = await UserAPI.getProfile();
    console.log("获取用户信息", response);
    // 假设根据 API 响应结构调整访问路径，这里假设 person 信息存储在 response.data 下
    if (response?.person) {
      currentUserPerson.value = response.person;
    }
  } catch (error) {
    console.error("获取用户信息失败", error);
  }
};

// 页面加载
onLoad((options) => {
  // 获取页面参数中的familyId
  if (options && options.familyId) {
    queryParams.familyId = Number(options.familyId);
  }
  getPageList();
  getUserInfo();
});

// 加载更多数据
onReachBottom(() => {
  loadmore();
});
const handleChange = (value: any) => {
  editForm.gender = value.value.splice(-1);
};
// 是否在世
const handleAliveChange = (value: any) => {
  editForm.alive = value.value.splice(-1);
};
// 获取家族成员分页列表
const getPageList = async () => {
  try {
    loadMoreState.value = "loading";
    const response = await PersonAPI.getPage(queryParams);

    // 判断响应是否为数组（旧版API）或对象（新版API）
    const list = Array.isArray(response) ? response : response.list || [];

    if (queryParams.pageNum === 1) {
      pageData.value = list;
    } else {
      pageData.value = [...pageData.value, ...list];
    }

    // 获取总数
    // 如果response是对象并且有total属性，使用该属性，否则使用数组长度
    total.value =
      !Array.isArray(response) && response.total !== undefined
        ? response.total
        : pageData.value.length;

    // 判断是否还有更多数据
    // 如果当前页数据为空，或者返回的数据长度小于每页大小，说明没有更多数据了
    const noMoreData = list.length === 0 || list.length < queryParams.pageSize;
    // 修复类型不匹配问题，确保赋值类型与LoadMoreState一致
    if (noMoreData) {
      loadMoreState.value = "nomore" as typeof loadMoreState.value;
    } else {
      loadMoreState.value = "loadmore" as typeof loadMoreState.value;
    }

    console.log("加载状态:", loadMoreState.value);

    // 默认排序
    handleSortChange();
  } catch (error) {
    console.error("获取家族成员列表失败", error);
    loadMoreState.value = "error";
    uni.showToast({
      title: "获取家族成员列表失败",
      icon: "none",
    });
  }
};
const loadmore = () => {
  // 只允许在"loadmore"状态下加载更多，避免类型不匹配的比较
  if (String(loadMoreState.value) !== "loadmore") return;
  queryParams.pageNum++;
  getPageList();
};

// 排序变更（前端排序）
const handleSortChange = () => {
  if (!pageData.value || pageData.value.length === 0) return;
  if (sortValue.value === 1) {
    // 最近创建
    pageData.value.sort((a: any, b: any) => (b.createTime || "").localeCompare(a.createTime || ""));
  } else if (sortValue.value === 2) {
    // 最近更新
    pageData.value.sort((a: any, b: any) => (b.updateTime || "").localeCompare(a.updateTime || ""));
  } else {
    // 默认排序（按id）
    pageData.value.sort((a: any, b: any) => (a.id || "").localeCompare(b.id || ""));
  }
};

// 重置查询条件
const handleResetQuery = () => {
  queryParams.lastName = "";
  queryParams.familyId = null;
  queryParams.pageNum = 1;
  filterDropMenu.value.close();
  getPageList();
};

// 执行查询
const handleQuery = () => {
  queryParams.pageNum = 1;
  filterDropMenu.value.close();
  getPageList();
};

// 查看详情
const handleViewDetail = (id: string) => {
  uni.navigateTo({
    url: `/pages/genealogy/person/detail?id=${id}`,
  });
};

// 查看家谱树
const handleViewTree = (item: any) => {
  uni.showActionSheet({
    itemList: ["查看家谱", "查看九族图", "查看十八代"],
    success: function (res) {
      // if(res.tapIndex === 0) {
      //   uni.navigateTo({
      //     url: `/pages/genealogy/person/tree?personId=${item.id}&familyId=${item.familyId}`
      //   });
      // }
      let url = "/pages/genealogy/person/tree?personId=" + item.id + "&familyId=" + item.familyId;
      if (res.tapIndex === 1) {
        url += "&viewType=nineFamily";
      } else if (res.tapIndex === 2) {
        url += "&viewType=eighteenGeneration";
      }
      uni.navigateTo({ url });
    },
    fail: function (res) {
      console.log(res.errMsg);
    },
  });
  // uni.navigateTo({
  //   url: `/pages/genealogy/person/tree?personId=${item.id}&familyId=${item.familyId}`
  // });
};

// 添加成员
const handleAddPerson = () => {
  console.log("添加成员");
  uni.navigateTo({
    url: "/pages/genealogy/createPerson/createPeron?familyId=" + queryParams.familyId,
  });
};

const handleEditPerson = async (id: string) => {
  editPopupVisible.value = true;
  try {
    const data = await PersonAPI.getFormData({ personId: id });
    Object.assign(editForm, {
      ...data,
      gender: [data.gender], // 包装为数组
      alive: [data.alive],
    }); // 填充表单
  } catch (e) {
    // @ts-ignore
    uni.showToast({
      title: "获取成员信息失败",
      icon: "none",
    });
  }
};

const handleSaveEdit = async () => {
  editForm.gender = editForm.gender[0];
  editForm.alive = editForm.alive[0];
  try {
    await PersonAPI.update(editForm);
    // @ts-ignore
    uni.showToast({
      title: "保存成功",
      icon: "success",
    });
    editPopupVisible.value = false;
    getPageList(); // 刷新列表
  } catch (e) {
    // @ts-ignore
    uni.showToast({
      title: "保存失败",
      icon: "none",
    });
  }
};

const onSearch = () => {
  queryParams.pageNum = 1; // 重置页码
  getPageList(); // 调用获取家族成员分页列表的方法
};

defineExpose({
  sortValue,
  sortOptions,
  handleSortChange,
  queryParams,
  handleResetQuery,
  handleQuery,
  pageData,
  handleViewDetail,
  handleViewTree,
  total,
  loadMoreState,
  loadmore,
  handleAddPerson,
  handleEditPerson,
  editPopupVisible,
  editForm,
  handleSaveEdit,
});
</script>

<style lang="scss" scoped>
.no-data-container {
  display: flex;
  justify-content: center;
  align-items: center;
}
.person-container {
  min-height: 100vh;
  background-color: #f8f8f8;

  .filter-container {
    padding: 10rpx;
    background: #fff;
  }

  .data-container {
    padding-bottom: 100rpx;
    padding-top: 20rpx;
    .wd-card {
      margin-bottom: 20rpx;
      border-radius: 12rpx;
      overflow: hidden;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
    }
  }

  .footer-block {
    display: flex;
    flex-direction: column;
    gap: 8rpx;
    padding: 10rpx 0 0 0;
  }
  .footer-btns {
    display: flex;
    justify-content: flex-end;
    gap: 10rpx;
    margin-top: 4rpx;
  }
  .flex-right {
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }
  .popup-footer {
    padding: 20rpx;
    display: flex;
    justify-content: space-around;
  }

  .flex-between {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .flex-center {
    display: flex;
    align-items: center;
  }

  .ml-2 {
    margin-left: 20rpx;
  }

  .mt-1 {
    margin-top: 10rpx;
  }

  .py-2 {
    padding-top: 20rpx;
    padding-bottom: 20rpx;
  }

  .font-bold {
    font-weight: bold;
  }

  .text-left {
    text-align: left;
  }

  .text-right {
    text-align: right;
  }
}

.row-flex {
  display: flex;
  gap: 16rpx;
}
.avatar-upload {
  margin: 16rpx 0;
}

.edit-form-card {
  background: #fff;
  border-radius: 24rpx 24rpx 0 0;
  padding: 16rpx 12rpx 8rpx 12rpx;
  margin-bottom: 0;
  box-shadow: 0 -2rpx 16rpx rgba(0, 0, 0, 0.06);
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  max-height: 60vh;
  overflow-y: auto;
}
.popup-footer {
  padding: 12rpx 12rpx 16rpx 12rpx;
  background: #fff;
  border-radius: 0 0 24rpx 24rpx;
}
.avatar-upload {
  display: flex;
  justify-content: start;
  margin: 8rpx 0;
  padding: 15px;
  .uni-label-pointer {
    min-width: 33% !important;
    max-width: 33% !important;
    font-size: 14px;
    margin-right: 15px;
  }
}

/* 扇形角标样式 */
.my-card {
  position: relative;
  overflow: visible;

  .corner-badge {
    position: absolute;
    top: -10rpx;
    right: -10rpx;
    width: 100rpx;
    height: 100rpx;
    background: linear-gradient(135deg, #ff6b6b 0%, #ff8e8e 100%);
    border-radius: 0 0 0 3.75rem;
    z-index: 10;
    overflow: hidden;

    .corner-text {
      position: absolute;
      top: 20rpx;
      left: 30rpx;
      color: white;
      font-size: 24rpx;
      font-weight: bold;
      transform: rotate(-45deg);
      transform-origin: center;
      white-space: nowrap;
    }
  }
}
</style>
